{% extends "base_extjs.html" %}

{% block extrahead %}
    {% include "gmap.html" %}
    <script src="{{MEDIA_URL}}/cwd/media/js/widgets.js" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[

    var map_panel = {
		title: 'Map',
		region: 'center',
		xtype: 'gmappanel',
		zoomLevel: 4,
		gmapType: 'map',
		//use_mgr: true,
		id: 'gridpoint_map',
		mapControls: ['GLargeMapControl','GMapTypeControl'],
                mapConfOpts: ['disableDoubleClickZoom'],
		width: 500,
		height: 600,
		setCenter: {
		    lat: 39,
		    lng: -102
		},
		gmap_listeners: {
		    click: function (marker,latlng) {
                        if ( marker ) {
                            setLatLonInputs(marker.getLatLng());
                        }
                        else {
                            var mark = createMarker(latlng.lat(), latlng.lng());
                            this.getMap().addOverlay(mark);
                            setLatLonInputs(mark.getLatLng());
                        }
		    }
		}
	    };

    var panels = new Ext.TabPanel({
                    region:'center',
                    deferredRender:true,
                    activeTab:0,
                    items:[map_panel]
                });

    function createGridPointMarker(g) {
        /* Given a Gridpoint object, return a GMapPanel marker object */
        var marker = new GMarker( new GLatLng(g.lat, g.lon), {icon: iconFuzzydotR} );
	return marker;
    }

    var gridpoints_store = new Ext.data.JsonStore({
        autoLoad: true,
        url: URL_PREFIX+'gridpoints/json/',
        root: 'gridpoints',
        fields: ['x','y','lat','lon'],
        markersToAdd: [],
        listeners: {
            'load': function(checkbox_obj,data,options) {
                        for( var i=0; i<data.length; i++ ) {
                            this.markersToAdd.push(createGridPointMarker( data[i].json ));
                        }
                    }
            }
    });
    

Ext.onReady(function(){

    var viewport = new Ext.Viewport({
            layout:'border',
            items:[
                new Ext.BoxComponent({ // raw
                    region:'north',
                    el: 'north',
                    height:32
                }), /*{
                    region:'south',
                    contentEl: 'south',
                    split:true,
                    height: 100,
                    minSize: 100,
                    maxSize: 200,
                    collapsible: true,
                    title:'South',
                    margins:'0 0 0 0'
                },*/ {
                    region:'east',
                    collapsible: true,
                    split:true,
                    width: 225,
                    minSize: 175,
                    maxSize: 400,
                    layout:'fit',
                    margins:'0 5 0 0',
                    items:
                        new Ext.Panel({
                            layout:'accordion',
                            layoutConfig:{ animate:true },
                            id: 'id_product_tabs',
                            border:false,
                            defaults: {
                                labelWidth: 50,
                                frame: true
                            },
                            activeItem: 0,
                            items:[
                             {
                                 contentEl: 'east-about',
                                 title:'How to use',
                                 frame: true,
                                 border:false
                             }, 
                             new Ext.FormPanel({
 			        title: "Monthly/Seasonal Listings",
                                id: "panel_monthly_listing",
				frame: true,
				labelWidth: 50,
  			        items: [ 
                                        new helpWindowButton({
                                                 contentEl: "monthly-seasonal-listings-help", 
                                                 winHeight: 400,
                                                 style: {marginBottom: '15px'}
                                        }),
                                        new latlonInput({name: 'lat', fieldLabel: 'Lat'}),
                                        new latlonInput({name: 'lon', fieldLabel: 'Lon'}),
                                        new spanSelect(), new monthSelect({fieldLabel:'End Month'}), new levelSelect(),
                                        new yearsSelect({fieldLabel:'Running average', name:'runavg'}),
                                        new unitsSelect(),
                                        new newPanelSubmit({ // must be last
                                            text: 'Go',
                                            src: URL_PREFIX+"products/bargraph_panel/"
                                        })
                                        ]
                                }),
			    new Ext.FormPanel({
				title: "Last 12 Months",
				frame: true,
				labelWidth: 50,
				items: [ 
                                        new helpWindowButton({
                                                 contentEl: "last-12-months-help", 
                                                 winHeight: 250,
                                                 style: {marginBottom: '15px'}
                                        }),
                                        new latlonInput({name: 'lat', fieldLabel: 'Lat'}),
                                        new latlonInput({name: 'lon', fieldLabel: 'Lon'}),
                                        new levelSelect(),
                                        new unitsSelect(),
                                        new newPanelSubmit({ // must be last
                                            text: 'Go',
                                            src: URL_PREFIX+"products/monthly_perc_panel/"
                                        })
                                        ]
                                }),
                             new Ext.FormPanel({
 			        title: "Monthly Precip as Snow",
                                id: "panel_monthly_precip",
				frame: true,
				labelWidth: 50,
  			        items: [ 
                                        new helpWindowButton({
                                                 contentEl: "monthly-precip-help", 
                                                 winHeight: 400,
                                                 style: {marginBottom: '15px'}
                                        }),
                                        new latlonInput({name: 'lat', fieldLabel: 'Lat'}),
                                        new latlonInput({name: 'lon', fieldLabel: 'Lon'}),
                                        new spanSelect(), new monthSelect({fieldLabel:'End Month'}), new PrecipLevelSelect(),
                                        new yearsSelect({fieldLabel:'Running average', name:'runavg'}),
                                        new newPanelSubmit({ // must be last
                                            text: 'Go',
                                            src: URL_PREFIX+"products/precip_bargraph_panel/"
                                        })
                                        ]
                                })
			    ]
                        })
                 },{
                    region:'west',
                    id:'west-panel',
                    split:true,
                    width: 200,
                    minSize: 175,
                    maxSize: 400,
                    collapsible: true,
                    margins:'0 0 0 5',
                    layout:'accordion',
                    layoutConfig:{
                        animate:true
                    },
                    activeItem: 0,
                    items: [{
                        contentEl: 'west-about',
                        title:'About',
                        frame: true,
                        border:false,
                        autoScroll: true
                    }, {
                        contentEl: 'west-contact',
                        title:'Contact',
                        frame: true,
                        border:false
                    }, {
                        contentEl: 'west-location',
                        title:'Location Selection',
                        frame: true,
                        border:false
                    }, new Ext.Panel({
                        title:'Display Options',
                        frame: true,
                        border:false,
                        items: [
                            new Ext.form.Checkbox({
                                    boxLabel: "Show grid points",
                                    checked: false,
                                    id: 'id_gridpoint_checkbox',
                                    listeners: {
                                        'check': function(checkbox, checked) {
                                            var gmap = Ext.getCmp('gridpoint_map').getMap();
                                            if (checked) {
                                                for( var i=0; i<gridpoints_store.markersToAdd.length; i++ ) {
                                                    gmap.addOverlay(gridpoints_store.markersToAdd[i]);
                                                }
                                            } else { // not checked
                                                for( var i=0; i<gridpoints_store.markersToAdd.length; i++ ) {
                                                    gmap.removeOverlay(gridpoints_store.markersToAdd[i]);
                                                }
                                            }
                                        }
                                    }
                                }),
                            {
                                xtype: 'panel',
                                html: 'Click “+” and “-“ buttons to highlight or minimize tabs. <br>To plot another product after completion of another product, click “Map” in middle tab, then click desired location on the map, or drag first marker to desired location.'
                            }
                        ]
                    })
                    ]
                }, panels
             ] // END viewport.items
        }); // END Viewport

    // Check for initial marker parameters in URL
    var urlparams = document.URL.split("?");
    if ( urlparams.length > 1 ) {
        var params = Ext.urlDecode(urlparams[1]);
        if ( "lat" in params && "lng" in params ) {
            var latlng = new GLatLng(params["lat"],params["lng"]);
            var mark = createMarker(latlng.lat(), latlng.lng());
            var gmap = Ext.getCmp('gridpoint_map').getMap();
            setLatLonInputs(latlng);
            gmap.addOverlay(mark);
            // For some reason, the center needs to be adjusted, so add 11.5 degrees
            gmap.setCenter(new GLatLng(latlng.lat(), latlng.lng() + 11.5),8);

            // open the product panel in the east viewport
            var prod = Ext.getCmp('panel_monthly_listing');
            prod.expand();
        }
    }
    }); // END onReady

    var monthNames = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    /* Create a marker at location latlng */
    function createMarker(lat,lng) {
	var marker = new GMarker( new GLatLng(lat,lng), {draggable: true} );
	GEvent.addListener(marker, "drag", setLatLonInputs );

	return marker;
    }

    function setLatLonInputs(latlng) {
        var container = Ext.getCmp('id_product_tabs');
        var p = container.findByType(Ext.FormPanel);
        Ext.each(p, function(){
            this.find('name', 'lat')[0].setValue(latlng.lat());
            this.find('name', 'lon')[0].setValue(latlng.lng());
        });
    }

   //]]>
    </script>
{% endblock %}

{% block body %}
<div id="west-about">
    <h3>Introduction</h3>
    <p>
    This analysis tool allows one to track through time the height of the freezing level (0 C or 32 F) above sea level.  Freezing level has important effects on hydrology in mountain environments.  This level affects 1) the elevation of the rain/snow line, 2) whether precipitation at a specified level falls as rain or as snow, 3) whether the ground is frozen or thawed when the first autumn snows fall, 4) the efficiency of snowpack accumulation through the winter months, 5) the internal temperature and rate of “ripening” and melting of the snowpack in the spring, and 6) the length of the snow free season at different elevations.  Freezing level also affects ecological function through biological growth rates (both plants and animals) at different elevations.  Other temperature thresholds of interest are available (10 C, 20 C, 30 C / 50 F, 68 F, 86 F) as well.  These temperatures can be substituted for the term “freezing level” below.
    </p>

    <h3>Definition</h3>
    <p>
    In the upper atmosphere temperatures are always below freezing everywhere on earth.  Starting from the upper atmosphere and working down, the freezing level is taken to be the elevation above sea level in the free atmosphere at which a temperature of 0 C (or 32 F) is first encountered.  The mean daily temperature profile used for this process is formed from the four six-hour averages available from Global Reanalysis (see below).
    </p>

    <h3>Monthly and seasonal means</h3>
    <p>
    Freezing level heights are found for each day.  When the entire atmosphere is cooler than freezing, values are set to zero meters above sea level for that day.  Monthly and seasonal values are the mean of all the daily values during that interval.  Topographic information is not included in the determination of freezing level.  This allows freezing level in mountainous or elevated regions to often be found below the topography. 
    Below the topography, the vertical rate of change of temperature ("lapse rate") is calculated by the Reanalysis, and is generally
    between 4.5 and 6.5 degrees C per kilometer. 
    </p>

    <h3>Monthly Precip as Snow</h3>
    <p id="monthly-precip-help">
    The purpose of this product is an
    estimate of the percent of precipitation
    at a given elevation that is falling
    as snow rather than rain during a certain
    portion of the year.  A user selects
    location, number of months, end month,
    running mean smoother, and an elevation.
    Precipitation is modeled amount from
    Global Reanalysis interpolated to point
    in question.  If temperature at the elevation
    and time is above 0 C, precipitation is
    considered to be rain, otherwise is snow.
    For the time interval in question, the amount
    of precip falling as rain is divided by the
    total amount of precipitation.  This ratio
    is expressed as a fraction from 0 to 100
    percent snow.  Lower numbers indicate
    more rain, less snow.
    </p>

    <h3>Data source</h3>
    <p>
    Values are based on the NCEP/NCAR Global Reanalysis determined every six hours from January 1948 until the last few days.  The grid spacing is approximately 2.5 x 2.5 degrees of latitude/longitude.  To see the grid, click the box under “settings” in the left hand frame.  Values are interpolated to the latitude/longitude selected.
    </p>
    <p>
    Means are from 1970-2000.
    </p>

    <h3>Acknowledgement</h3>
    <p>
    Development of the North American Freezing Level Tracker was funded by the National Oceanic and Atmospheric Administration (NOAA) through the Regional Integrated Sciences and Assessments (RISA) Program under the Coping With Drought element.
    </p>
</div>
<div id="west-contact">
    <p>
    For questions, questions, or web problems, contact wrcc@dri.edu, 775-674-7010, or kelly.redmond@dri.edu.  John Abatzoglou at the University of Idaho (jabatzoglou@uidaho.edu) programmed most of the code.
    </p>
</div>
<div id="west-location">
    <p>
    Click anywhere on the map to place a marker.  This marker can subsequently be dragged around the map.  Use the Products panel on the right to generate products for the marker's location.
    </p>
    <p>
    To see available locations, select the <strong>Display Options</strong> tab, and check <em>Show Grid Points</em>.
    </p>
</div>
<div id="east-about">
    <p>
    Select products below.  Products appear in middle panel.
    Previous products can be retrieved from middle of top line, or deleted by clicking “X” in upper right of each graphic.  Use “save as” to retain graphic.
    To plot another product after completion of a previous product, 
    click “Map” in middle tab and then click another desired location on the map.  
    Or, drag first marker to desired location.
    </p>
</div>
<div id="north">
    <h1 style="color: #303099; padding-left: 0; margin-left: 0;">
    <img src="{{MEDIA_URL}}/cwd/media/img/NAFLT_logo2.png" style="margin:0; padding:0; vertical-align:top;" />
    North American Freezing Level Tracker</h1>
</div>
<div id="props-panel" style="width:200px;height:200px;overflow:hidden;">
</div>
  <!--
  <div id="south">
    <p>south - generally for informational stuff, also could be for status bar</p>
  </div>
  -->
<div id="monthly-seasonal-listings-help" class="x-hidden">
<h3>Monthly/seasonal Time Series</h3>
<p>
This product shows the mean height of the selected temperature value for the same portion of each year through the latest available year.  
Use the pulldowns to select a month or season.  A “season” is a period of 2 or more months extending through the end of the selected month.  
To select December through February, for example, select the three months (“span”) ending in February (“End Month”).  
Four temperature values are available:  0 C (the “freezing level”), +10 C, +20 C, and +30 C.  
These other values are of interest to ecologists and biologists.  Latitude and longitude can be selected by clicking on the map, 
or by direct entry in the form.  The running average is computed as the mean over the indicated number of years (“Running Average”), 
and is plotted at the midpoint of each such period, and shown as a black line.  The long-term mean value for the overall 
period is plotted as a horizontal line.  Years with values reflecting warmer than usual conditions are shown in red, 
and values reflecting cooler than usual conditions are shown in blue.
</p>
</div>

<div id="last-12-months-help" class="x-hidden">
    <h3>Last 12 Months</h3>
    <p>
    Shows the recent history of the height of the selected temperature value for each of the last twelve full months. 
    Latitude and longitude can be selected by clicking on the map, or by direct entry in the form.  
    Red:  Values for the most recent 12 months.  
    Black:  Long-term median for each of the most recent 12 months.  
    Blue shading:  from bottom, 5th, 10th, 25th, 50th, 75th, 90th, 95th percentile for each month, for period of record (1948 through latest month).
    </p>
</div>
{% endblock %}
